﻿Imports System.Runtime.InteropServices
Imports System.Windows.Forms

Public Module FormProcess
    <DllImport("User32.dll", EntryPoint:="SendMessage")> Public Function SendMessage(ByVal hWnd As IntPtr, ByVal Msg As Integer, ByVal wParam As IntPtr, ByVal lParam As String) As Integer
    End Function

    <DllImport("User32.dll", EntryPoint:="SendMessage")> Public Function SendMessage(ByVal hWnd As IntPtr, ByVal Msg As Integer, ByVal wparam As Integer, ByVal lParam As Integer) As Integer
    End Function

    <DllImport("user32.dll", EntryPoint:="SendMessage", SetLastError:=True, CharSet:=CharSet.Auto)> Private Function SendMessage(ByVal hwnd As IntPtr, ByVal wMsg As UInt32, ByVal wParam As Integer, ByVal lParam As Integer) As Integer
    End Function

    <DllImport("user32.dll", CharSet:=CharSet.Unicode)> Public Function SendMessage(ByVal hwnd As IntPtr, ByVal wMsg As Integer, ByVal wparam As Boolean, ByVal lParam As Integer) As IntPtr
    End Function
    <DllImport("user32.dll", EntryPoint:="RedrawWindow")> Public Function RedrawWindow(<System.Runtime.InteropServices.InAttribute()> ByVal hWnd As System.IntPtr, <System.Runtime.InteropServices.InAttribute()> ByVal lprcUpdate As System.IntPtr, <System.Runtime.InteropServices.InAttribute()> ByVal hrgnUpdate As System.IntPtr, ByVal flags As UInt32) As Boolean
    End Function
    Public Function CreateFormInstance(mWindowChild As String, FrmMain As Form, frmMainins As Form) As Boolean
        Dim ret As Integer
        '查找当前项目中的所有窗口(Form)的子类
        For Each item As Type In FrmMain.GetType().Assembly.GetTypes()
            If item.IsSubclassOf(GetType(Form)) AndAlso item.Name = mWindowChild Then
                '判断该窗体是否已经打开
                For Each mChilewin As Form In frmMainins.MdiChildren
                    '检测是不是当前子窗体名称,如果窗体存在直接激活返回
                    If mChilewin.Name = mWindowChild Then
                        ret = SendMessage(FrmMain.Handle, &HB, 0, 0)
                        mChilewin.Activate()
                        mChilewin.WindowState = FormWindowState.Maximized
                        ret = SendMessage(FrmMain.Handle, &HB, 1, 0)
                        RedrawWindow(FrmMain.Handle, System.IntPtr.Zero, System.IntPtr.Zero, &H491)
                        Return True
                    End If
                Next
                '找到窗口子类并且为指定名称,那么使用基类的模板打开它.
                Dim v As Form = CType(item.GetConstructor(Type.EmptyTypes).Invoke(Nothing), Form)
                v.MdiParent = FrmMain
                v.WindowState = FormWindowState.Maximized
                ret = SendMessage(FrmMain.Handle, &HB, 0, 0)
                v.Show()
                ret = SendMessage(FrmMain.Handle, &HB, 1, 0)
                RedrawWindow(FrmMain.Handle, System.IntPtr.Zero, System.IntPtr.Zero, &H491)
                Return False
            End If
        Next
        Return False
    End Function
End Module
